#include "ADS1256.h"

uint8_t SPI_WRByte(uint8_t TxData)
{
	uint8_t RxData=0; 
	HAL_SPI_TransmitReceive(&hspi3, &TxData, &RxData, 1, 0x0F);
	return RxData;
}	

void ADS1256WREG(uint8_t addr,uint8_t data)
{	
	CS_0;
	while(ADS1256_DRDY); //wait for data ready
	
	SPI_WRByte(ADS1256_CMD_WREG|(addr&0x0F));
	SPI_WRByte(0x00);
	SPI_WRByte(data);
	
	CS_1;
}

void ADS1256CMD(uint8_t cmd)
{
	SPI_WRByte(cmd);
}

void ADS1256_Init()
{
	while(ADS1256_DRDY);
	CS_0;
	ADS1256CMD(ADS1256_CMD_SELFCAL);//self calibration
	while(ADS1256_DRDY);
	CS_1;

	while(ADS1256_DRDY);
	ADS1256WREG(ADS1256_STATUS,0x06);
	ADS1256WREG(ADS1256_ADCON,ADS1256_GAIN_1); 
	ADS1256WREG(ADS1256_DRATE,ADS1256_DRATE_10SPS);
	ADS1256WREG(ADS1256_IO,0x00);             

	while(ADS1256_DRDY);
	CS_0;
	ADS1256CMD(ADS1256_CMD_SELFCAL);
	while(ADS1256_DRDY);
	CS_1;
}

int32_t ADS1256_ReadData(uint8_t channel)
{
	uint32_t sum=0;

	while(ADS1256_DRDY);
	ADS1256WREG(ADS1256_MUX,channel);

	CS_0;

	ADS1256CMD(ADS1256_CMD_SYNC);
	ADS1256CMD(ADS1256_CMD_WAKEUP);
	ADS1256CMD(ADS1256_CMD_RDATA);

	HAL_Delay(1);

	sum |= (SPI_WRByte(0xff) << 16);
	sum |= (SPI_WRByte(0xff) << 8);
	sum |= (SPI_WRByte(0xff));

	CS_1;

	 if (sum>0x7FFFFF)           // if MSB=1, 
	 	sum -= 0x1000000;       // do 2's complement

	return sum;	
}